<?php

require_once 'Zend/Loader.php';

Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');


/**
 * Class that contains all simple operations for Dation Blogger. 
 * Niek Hoogma, 07-08-2008,
 * v1.0
 *
 */
class DationBlog
{
    // $blogID - Blog ID used @ google blogger
     public $blogID; 

    //$gdClient - Client class used to communicate with the Blogger service
    public $gdClient; 
    

    /**
     * Constructor for the class. 
     */
    public function __construct()
    {
    		$this->blogID = $_SESSION['config']['blogID'];
    		$email = $_SESSION['config']['blogEmail'];
    		$password = $_SESSION['config']['blogPassword'];
    		
    		$client = Zend_Gdata_ClientLogin::getHttpClient($email, $password, 'blogger');
        $this->gdClient = new Zend_Gdata($client);
    }
   
    /**
     * This function creates a new Zend_Gdata_Entry representing a blog
     * post, and inserts it into the user's blog. It also checks for
     * whether the post should be added as a draft or as a published
     * post.
     *
     * @param  string  $title   The title of the blog post.
     * @param  string  $content The body of the post.
     * @param  boolean $isDraft Whether the post should be added as a draft or as a published post
     * @return string The newly created post's ID
     */
    public function createPost($title, $content, $isDraft=False)
    {
        // We're using the magic factory method to create a Zend_Gdata_Entry.
        // http://framework.zend.com/manual/en/zend.gdata.html#zend.gdata.introdduction.magicfactory
        $entry = $this->gdClient->newEntry();
    
        $entry->title = $this->gdClient->newTitle(trim($title));
        $entry->content = $this->gdClient->newContent(trim($content));
        $entry->content->setType('text'); 
        $uri = "http://www.blogger.com/feeds/" . $this->blogID . "/posts/default";  
        
        if ($isDraft)
        {
            $control = $this->gdClient->newControl(); 
            $draft = $this->gdClient->newDraft('yes');
            $control->setDraft($draft);  
            $entry->control = $control; 
        }        

        $createdPost = $this->gdClient->insertEntry($entry, $uri);
        //format of id text: tag:blogger.com,1999:blog-blogID.post-postID 
        $idText = split('-', $createdPost->id->text);
        $postID = $idText[2];

        return $postID; 
    }
    
    /**
     * Returns all the posts in the user's blog.
     *
     * @return array
     */
    public function getPosts($params = array(),$category = array())
    {
    		$query = new Zend_Gdata_Query('http://www.blogger.com/feeds/' . $this->blogID . '/posts/default');
        
        foreach($params as $key => $value) {
        	$query->setParam($key,$value);
        }
				
				if (count($category) > 0) {
					// setCategory expects a string
					$cat_url = implode("/", $category);
					$query->setCategory($cat_url);
        }
        
        // echo $query->getQueryUrl();
        
        $feed = $this->gdClient->getFeed($query); 
        
        $res = array();
        
        $entries = array();
        foreach ($feed->entries as $key => $value) {
        	$entries[] = DationBlog::convertEntryToDationBlogEntry($value);
        }
        
        $res['entries'] = $entries;
        $res['totalResults'] = (int)$feed->totalResults->text;
        $res['startIndex'] = (int)$feed->startIndex->text;
        $res['itemsPerPage'] = (int)$feed->itemsPerPage->text;
        return $res;
    }

    /**
     * Retrieves the specified post and updates the title and body. Also sets
     * the post's draft status.
     *
     * @param string  $postID         The ID of the post to update. PostID in <id> field:
     *                                tag:blogger.com,1999:blog-blogID.post-postID
     * @param string  $updatedTitle   The new title of the post.
     * @param string  $updatedContent The new body of the post.
     * @param boolean $isDraft        Whether the post will be published or saved as a draft.
     * @return Zend_Gdata_Entry The updated post. 
     */
    public function updatePost($postID, $updatedTitle, $updatedContent, $isDraft)
    {
        $query = new Zend_Gdata_Query('http://www.blogger.com/feeds/' . $this->blogID . '/posts/default/' . $postID); 
        $postToUpdate = $this->gdClient->getEntry($query);
        $postToUpdate->title->text = $this->gdClient->newTitle(trim($updatedTitle));
        $postToUpdate->content->text = $this->gdClient->newContent(trim($updatedContent));

        if ($isDraft) {
            $draft = $this->gdClient->newDraft('yes'); 
        } else {
            $draft = $this->gdClient->newDraft('no');
        }
   
        $control = $this->gdClient->newControl();
        $control->setDraft($draft);
        $postToUpdate->control = $control;
        $updatedPost = $postToUpdate->save();
        
        return $updatedPost; 
    }
    
    /** 
     * This function creates a new comment and adds it to the specified post.
     * A comment is created as a Zend_Gdata_Entry.
     *
     * @param  string $postID      The ID of the post to add the comment to. PostID
     *                             in the <id> field: tag:blogger.com,1999:blog-blogID.post-postID
     * @param  string $commentText The text of the comment to add. 
     * @return string The ID of the newly created comment.
     */
    public function createComment($postID, $commentText)
    {
        $uri = 'http://www.blogger.com/feeds/' . $this->blogID . '/' . $postID . '/comments/default'; 
        
        $newComment = $this->gdClient->newEntry(); 
        $newComment->content = $this->gdClient->newContent($commentText); 
        $newComment->content->setType('text'); 
        $createdComment = $this->gdClient->insertEntry($newComment, $uri); 
        
        echo 'Added new comment: ' . $createdComment->content->text . "\n";
        // Edit link follows format: /feeds/blogID/postID/comments/default/commentID 
        $editLink = split('/', $createdComment->getEditLink()->href);
        $commentID = $editLink[8];      
 
        return $commentID; 
    }

    /** 
     * This function gets all comments associated with the specified post.
     *
     * @param  string $postID The ID of the post whose comments we'll print.
     * @return array() containing feeds
     */
    public function getAllComments($postID)
    {
        $query = new Zend_Gdata_Query('http://www.blogger.com/feeds/' . $this->blogID . '/' . $postID . '/comments/default'); 
        $feed = $this->gdClient->getFeed($query);
        $res = array();
				foreach ($feed->entries as $key => $value) {
        	$res[] = DationBlog::convertEntryToDationBlogEntry($value);
        }
        return $res;
    }

    /** 
     * This function deletes the specified comment from a post.
     *
     * @param  string $postID    The ID of the post where the comment is. PostID in
     *                           the <id> field: tag:blogger.com,1999:blog-blogID.post-postID
     * @param  string $commentID The ID of the comment to delete. The commentID
     *                           in the editURL: /feeds/blogID/postID/comments/default/commentID
     * @return void 
     */
    public function deleteComment($postID, $commentID)
    {
        $uri = 'http://www.blogger.com/feeds/' . $this->blogID . '/' . $postID . '/comments/default/' . $commentID; 
        $this->gdClient->delete($uri); 
    }

    /** 
     * This function deletes the specified post.
     *
     * @param  string $postID The ID of the post to delete.
     * @return void
     */
    public function deletePost($postID)
    {
        $uri = 'http://www.blogger.com/feeds/' . $this->blogID . '/posts/default/' . $postID; 
        $this->gdClient->delete($uri);  
    }
    
    /**
     * This functions wraps an feed entry to a DationBlogEntry object
     *
     * @param string $entry The entry wrapped into a blogger object
     * @return DationBlogEntry The generated blogentry
     */
     
    public static function convertEntryToDationBlogEntry($entry) {
    	$dbe = new DationBlogEntry();
    	$dbe->set_id($entry->id->text);
    	$dbe->set_published($entry->published->text);
    	$dbe->set_updated($entry->updated->text);
    	$dbe->set_title(utf8_decode($entry->title->text));
    	$dbe->set_content(utf8_decode($entry->content->text));
    	@$dbe->set_authors(current($entry->author)->name->text);
    	
    	$categories = array();
    	foreach ($entry->category as $key => $value) {
    			$categories[] = $value->term;
    	}    	
    	$dbe->set_labels($categories);
    	return $dbe;
    }
    
    public function getCategories()
    {
    		/**
    		$query = new Zend_Gdata_Query('http://www.blogger.com/feeds/' . $this->blogID . '/blogs');
        $feed = $this->gdClient->getFeed($query); 
				print_r($feed);
				exit;
				*/
			  $query = new Zend_Gdata_Query('http://www.blogger.com/feeds/default/blogs');
			  $feed = $this->gdClient->getFeed($query);
			  
			  
			  $res = array();
			  
			  // There can be multiple blogs defined
  			foreach($feed as $b) {
  			
  				// Check every category
  				foreach($b->category as $cat) {
  					if(!in_array($cat->term,$res)) {
  						$res[] = $cat->term;
  					}
  				}
  			}
  			
  			return $res;

    }
}